extends RigidBody2D

const jump_force: float = 6000.0
const move_deacy: float = 10.0

var move_speed: float = 3000.0
var acc = move_speed / 0.1

var qianyin_force: Vector2 = Vector2.ZERO

var velocity = 0.0

var direction = 0

var was_on_floor = false
var is_on_floor = false
var last_y = 0.0

onready var parent = get_parent()

onready var coyote_timer = $CoyoteTimer
onready var jump_request_timer = $JumpRequestTimer

func _physics_process(delta: float) -> void:
	angular_velocity = -rotation * 10 # 角度恢复为0
	
	direction = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
	direction *= parent.nega
	if direction != 0:
		velocity = direction * move_speed
	else:
		velocity = 0
		
	linear_velocity.x = move_toward(linear_velocity.x, velocity, delta * acc)
	# print(linear_velocity.x)
		
	# linear_velocity += qianyin_force
	
	was_on_floor = is_on_floor
	
	if abs(position.y - last_y) < 1 and not get_colliding_bodies().empty():
		is_on_floor = true
	else:
		is_on_floor = false
		last_y = position.y
		
	if was_on_floor and not is_on_floor:
		coyote_timer.start()
	
	
func _input(event: InputEvent) -> void:
	if event.is_action_pressed("jump")\
		or event.is_action_pressed("move_up"):
		jump_request_timer.start()
	elif event.is_action_released("jump") and linear_velocity.y < -jump_force / 2:
		linear_velocity.y = - jump_force / 2

func _process(delta: float) -> void:
	var can_jump = is_on_floor or coyote_timer.time_left > 0
	if can_jump and jump_request_timer.time_left > 0:
		linear_velocity.y = -jump_force
		jump_request_timer.stop()
		coyote_timer.stop()



